﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;

public class SpriteAtlasEditor
{
    private const float MaxTextureSize = 1024;
    private const string AtlasNameFormat = "__{0}_Atlas.spriteatlas";

    [MenuItem("Assets/资源/打包图集")]
    public static void CreateSpriteAtlas()
    {
        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Assets);

        foreach (Object tmpFolder in SelectedAsset)
        {
            string filepath = AssetDatabase.GetAssetPath(tmpFolder);
            if (!string.IsNullOrEmpty(filepath))
            {
                if (!Directory.Exists(filepath))
                {
                    Debug.LogError("路径不存在.." + filepath);
                    return;
                }
                else
                {
                    Debug.Log("当前选择路径为:" + filepath);
                }

                int index = filepath.IndexOf("/");
                string seekPath = filepath.Substring(index);
                List<string> pathList = __GetAllSprite(seekPath);
                int lastIdx = filepath.LastIndexOf("/");
                string name = filepath.Substring(lastIdx + 1);
                string savePath = string.Format("{0}/{1}", filepath, string.Format(AtlasNameFormat, name));
                // Debug.LogError("..." + savePath);
                __Create(savePath, pathList);
            }
        }
    }

    [MenuItem("便捷工具/资源操作/更新所有已生成的图集")]
    public static void UpdateAllSpriteAtlas()
    {
        List<string> withoutExtensions = new List<string>() { ".spriteatlas" };
        string[] files = Directory.GetFiles(Application.dataPath, "*.*", SearchOption.AllDirectories).Where(s => withoutExtensions.Contains(Path.GetExtension(s).ToLower())).ToArray();
        foreach (var path in files)
        {
            FileInfo info = new FileInfo(path);
            int pos = info.Directory.FullName.IndexOf("Assets");
            string filepath = "Assets" + @info.Directory.FullName.Substring(pos + "Assets".Length);
            Debug.Log(filepath);
            int index = filepath.IndexOf(@"\");
            string seekPath = filepath.Substring(index);
            List<string> pathList = __GetAllSprite(seekPath);
            int lastIdx = filepath.LastIndexOf(@"\");
            string name = filepath.Substring(lastIdx + 1);
            string savePath = string.Format(@"{0}\{1}", filepath, string.Format(AtlasNameFormat, name));
            // Debug.LogError("..." + savePath);
            __Create(savePath, pathList);
        }
    }
    public static void __Create(string savePath, List<string> pathList)
    {
        var spriteAtlas = new SpriteAtlas();
        SpriteAtlasPackingSettings packingSettings = spriteAtlas.GetPackingSettings();
        packingSettings.enableTightPacking = false;
        spriteAtlas.SetPackingSettings(packingSettings);
        foreach (var assetPath in pathList)
        {
            var sprite = AssetDatabase.LoadAssetAtPath<Sprite>(assetPath);
            List<Object> packables = new List<Object>(spriteAtlas.GetPackables());
            if (!packables.Contains(sprite))
            {
                spriteAtlas.Add(new Object[] { sprite });
            }
        }
        //默认平台
        var atlasSetting = spriteAtlas.GetPlatformSettings("DefaultTexturePlatform");
        atlasSetting.maxTextureSize = 1024;
        atlasSetting.textureCompression = TextureImporterCompression.Uncompressed;
        atlasSetting.format = TextureImporterFormat.RGBA32;
        spriteAtlas.SetPlatformSettings(atlasSetting);
        //PC平台
        var pcAtlasSetting = spriteAtlas.GetPlatformSettings("Standalone");
        pcAtlasSetting.overridden = true;
        pcAtlasSetting.maxTextureSize = 1024;
        pcAtlasSetting.textureCompression = TextureImporterCompression.CompressedHQ;
        pcAtlasSetting.format = TextureImporterFormat.RGBA32;
        spriteAtlas.SetPlatformSettings(pcAtlasSetting);
        //安卓平台
        var andoridAtlasSetting = spriteAtlas.GetPlatformSettings("Android");
        andoridAtlasSetting.overridden = true;
        andoridAtlasSetting.maxTextureSize = 1024;
        andoridAtlasSetting.textureCompression = TextureImporterCompression.CompressedHQ;
        andoridAtlasSetting.format = TextureImporterFormat.ETC2_RGBA8;
        spriteAtlas.SetPlatformSettings(andoridAtlasSetting);
        //IOS平台
        var iosAtlasSetting = spriteAtlas.GetPlatformSettings("iPhone");
        iosAtlasSetting.overridden = true;
        iosAtlasSetting.maxTextureSize = 1024;
        iosAtlasSetting.textureCompression = TextureImporterCompression.CompressedHQ;
        iosAtlasSetting.format = TextureImporterFormat.RGBA32;
        spriteAtlas.SetPlatformSettings(iosAtlasSetting);

        AssetDatabase.CreateAsset(spriteAtlas, savePath);
    }

    private static List<string> __GetAllSprite(string path)
    {
        List<string> spriteList = new List<string>();
        string filePath = string.Format("{0}{1}", Application.dataPath, path);
        string[] files = Directory.GetFiles(filePath, "*.*", SearchOption.AllDirectories);
        if (files != null)
        {
            string extension = string.Empty;
            string tempPath = string.Empty;
            for (int i = 0; i < files.Length; ++i)
            {
                extension = Path.GetExtension(files[i]);
                if (extension.Equals(".png") || extension.Equals(".jpg"))
                {
                    string p = files[i].Substring(files[i].IndexOf("Asset")).Replace('\\', '/');
                    Texture2D t = AssetDatabase.LoadAssetAtPath<Texture2D>(p);
                    int maxSize = t.width > t.height ? t.width : t.height;
                    if (maxSize > MaxTextureSize)
                    {
                        Debug.Log(string.Format("{0}={1}*{2},文件尺寸过大，不打入图集..", files[i], t.width, t.height));
                        continue;
                    }
                    tempPath = files[i].Substring(files[i].IndexOf("Asset")).Replace('\\', '/');
                    spriteList.Add(tempPath);
                }
            }
        }
        return spriteList;
    }

    private static string __GetPlatformName(BuildTarget target)
    {
        string platformName = "";
        switch (target)
        {
            case BuildTarget.Android:
                platformName = "Android";
                break;
            case BuildTarget.iOS:
                platformName = "iPhone";
                break;
            case BuildTarget.PS4:
                platformName = "PS4";
                break;
            case BuildTarget.XboxOne:
                platformName = "XboxOne";
                break;
            case BuildTarget.NoTarget:
                platformName = "DefaultTexturePlatform";
                break;
            default:
                platformName = "Standalone";
                break;
        }
        return platformName;
    }

    [MenuItem("Assets/资源/检测目录，长宽不为4的倍数的图片")]
    public static void CheckTextureWidthHeight4()
    {
        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Assets);

        foreach (Object asset in SelectedAsset)
        {
            string filepath = AssetDatabase.GetAssetPath(asset);

            //Debug.LogError("图片资源->" + filepath,FindResWindows.GetLogObject(asset));
            if (!string.IsNullOrEmpty(filepath))
            {
                if (!Directory.Exists(filepath))
                {
                    Debug.LogError("路径不存在.." + filepath);
                    return;
                }
                else
                {
                    //Debug.Log("当前选择路径为:" + filepath);
                }

                int index = filepath.IndexOf("/");
                string seekPath = filepath.Substring(index);
                List<string> pathList = __GetAllSizeSprite(seekPath, DivisionType.notDivision4);
                Debug.Log("----------------------------------------start-------------------------------------------");
                Debug.LogWarning("---------------总数:" + pathList.Count);
                foreach (var item in pathList)
                {
                    Debug.Log("item->" + item);
                }
                Debug.Log("----------------------------------------end-------------------------------------------");

            }
        }

    }
    public static void CheckTextureWidthHeight2()
    {
        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Assets);

        foreach (Object asset in SelectedAsset)
        {
            string filepath = AssetDatabase.GetAssetPath(asset);
            if (!string.IsNullOrEmpty(filepath))
            {
                int index = filepath.IndexOf("/");
                string seekPath = filepath.Substring(index);
                List<string> pathList = __GetAllSizeSprite2(seekPath, DivisionType.notDivision4);
                Debug.Log("----------------------------------------start-------------------------------------------");
                Debug.LogWarning("---------------总数:" + pathList.Count);
                foreach (var path in pathList)
                {
                    Debug.Log("" + path,FindResWindows.GetLogObject(path));
                }
                Debug.Log("----------------------------------------end-------------------------------------------");
            }
        }

    }

    [MenuItem("Assets/资源/设置成(2048，ETC2_RGBA8Crunched)")]
    private static void CheckTextureAndSet()
    {
        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Assets);

        foreach (Object tmpFolder in SelectedAsset)
        {
            string filepath = AssetDatabase.GetAssetPath(tmpFolder);
            if (!string.IsNullOrEmpty(filepath))
            {
                if (!Directory.Exists(filepath))
                {
                    Debug.LogError("路径不存在.." + filepath);
                    return;
                }
                else
                {
                    Debug.Log("当前选择路径为:" + filepath);
                }

                int index = filepath.IndexOf("/");
                string seekPath = filepath.Substring(index);
                List<string> pathList = __GetAllSizeSprite(seekPath,DivisionType.division4);
                foreach (var item in pathList)
                {
                    SetTextureImport(item, "Android");
                    Debug.Log("设置成功："+ item);
                }
            }
        }

    }


    private enum DivisionType { 
        all,
        division4,
        notDivision4,
    }
    private static void SetTextureImport(string path, string platform, int size = 2048, TextureImporterFormat format = TextureImporterFormat.ETC2_RGBA8Crunched)
    {
        TextureImporter texImport = AssetImporter.GetAtPath(path) as TextureImporter;
        TextureImporterPlatformSettings settingIns = texImport.GetPlatformTextureSettings(platform);
        settingIns.overridden = true;
        settingIns.maxTextureSize = size;
        settingIns.format = format;
        texImport.SetPlatformTextureSettings(settingIns);
    }

    private static List<string> __GetAllSizeSprite(string path, DivisionType division4)
    {
        List<string> spriteList = new List<string>();
        string filePath = string.Format("{0}{1}", Application.dataPath, path);
        string[] files = Directory.GetFiles(filePath, "*.*", SearchOption.AllDirectories);
        if (files != null)
        {
            string extension = string.Empty;
            string tempPath = string.Empty;
            for (int i = 0; i < files.Length; ++i)
            {
                extension = Path.GetExtension(files[i]);
                if (extension.Equals(".png") || extension.Equals(".jpg"))
                {
                    string p = files[i].Substring(files[i].IndexOf("Asset")).Replace('\\', '/');
                    Texture2D t = AssetDatabase.LoadAssetAtPath<Texture2D>(p);
                    tempPath = files[i].Substring(files[i].IndexOf("Asset")).Replace('\\', '/');

                    switch (division4)
                    {

                        case DivisionType.division4:
                            if (t.width % 4 == 0 && t.height % 4 == 0)
                            {
                                spriteList.Add(tempPath);
                            }
                            break;
                        case DivisionType.notDivision4:
                            if (t.width % 4 != 0 || t.height % 4 != 0)
                            {
                                spriteList.Add(tempPath);
                            }

                            break;
                        case DivisionType.all:
                            spriteList.Add(tempPath);
                            break;
                    }

                }
            }
        }
        return spriteList;
    }

    private static List<string> __GetAllSizeSprite2(string path, DivisionType division4)
    {
        List<string> spriteList = new List<string>();
        string filePath = string.Format("{0}{1}", Application.dataPath, path);
        DirectoryInfo info = new DirectoryInfo(filePath);
        Debug.Log(info.FullName);
        string[] files = Directory.GetFiles(info.FullName, "*.*", SearchOption.AllDirectories);
        if (files != null)
        {
            string extension = string.Empty;
            string tempPath = string.Empty;
            for (int i = 0; i < files.Length; ++i)
            {
                extension = Path.GetExtension(files[i]);
                if (extension.Equals(".png") || extension.Equals(".jpg"))
                {
                    string p = files[i].Substring(files[i].IndexOf("Asset")).Replace('\\', '/');
                    Texture2D t = AssetDatabase.LoadAssetAtPath<Texture2D>(p);
                    tempPath = files[i].Substring(files[i].IndexOf("Asset")).Replace('\\', '/');

                    switch (division4)
                    {

                        case DivisionType.division4:
                            if (t.width % 2 == 0 && t.height % 2 == 0)
                            {
                                spriteList.Add(tempPath);
                            }
                            break;
                        case DivisionType.notDivision4:
                            if (t.width % 2 != 0 || t.height % 2 != 0)
                            {
                                spriteList.Add(tempPath);
                            }

                            break;
                        case DivisionType.all:
                            spriteList.Add(tempPath);
                            break;
                    }

                }
            }
        }
        return spriteList;
    }
}
